package tech.aistar.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.aistar.pojo.Order;
import tech.aistar.mapper.OrderMapper;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    public Order createOrder(Order order) {
        // 生成唯一订单号
        String orderNo = generateOrderNo();
        order.setOrderNo(orderNo);
        order.setCreateTime(LocalDateTime.now());
        order.setStatus("pending"); // 待支付

        orderMapper.insert(order);
        return order;
    }

    public Order getOrderById(Long id) {
        return orderMapper.findById(id);
    }

    public Order getOrderByNo(String orderNo) {
        return orderMapper.findByOrderNo(orderNo);
    }

    public List<Order> getOrdersByUser(Long userId) {
        return orderMapper.findByUserId(userId);
    }

    public boolean updateOrderStatus(Long orderId, String status) {
        Order order = orderMapper.findById(orderId);
        if (order != null) {
            order.setStatus(status);
            if ("paid".equals(status)) {
                order.setPayTime(LocalDateTime.now());
            }
            return orderMapper.updateStatus(order) > 0;
        }
        return false;
    }

    public boolean cancelOrder(Long orderId) {
        return updateOrderStatus(orderId, "cancelled");
    }

    private String generateOrderNo() {
        return LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")) +
                UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }

    public List<Order> getAll() {
        return orderMapper.findAll();
    }
}
